package com.mzj.saas.mservice.smartlock.service.huixiangjia;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.Repository.SmartLockBleRepository;
import com.mzj.saas.mservice.lock.entity.SmartLockBle;
import com.mzj.saas.mservice.lock.entity.SmartLockCard;
import com.mzj.saas.mservice.lock.entity.SmartLockFace;
import com.mzj.saas.mservice.lock.entity.SmartLockPwd;
import com.mzj.saas.mservice.oss.service.OSSService;
import com.mzj.saas.mservice.smartlock.base.BaseLock;
import com.mzj.saas.mservice.smartlock.service.huixiangjia.util.AESUtil;
import com.mzj.saas.mservice.smartlock.service.huixiangjia.util.RandomPhoneNumGenerator;
import com.mzj.saas.mservice.smartlock.vo.DevMacStateVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockFingerprintVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 慧享佳-智能锁接口
 */
@Slf4j
@Service
public class SmartLockHxjService implements BaseLock {

    @Value("${huiXiangJia.url}")
    private String huiXiangJiaUrl;
    @Value(("${huiXiangJia.accountName}"))
    private String huiXiangJiaAccountName;
    @Value("${huiXiangJia.password}")
    private String huiXiangJiaPassword;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OSSClient ossClient;


    /**
     * 获取慧享佳平台token
     *
     * @return token
     */
    public String getToken() {
        String token = redisTemplate.opsForValue().get("sys_huiXiangJiaToken");
        if (StrUtil.isBlank(token)) {
            try {
                Map<String, Object> dataMap = new HashMap<>(4);
                dataMap.put("accountName", huiXiangJiaAccountName);
                dataMap.put("password", huiXiangJiaPassword);
                Map<String, Object> paramsMap = new HashMap<>(4);
                paramsMap.put("method", "apartmentLogin");
                paramsMap.put("data", dataMap);
                log.info("慧享佳--鉴权接口请求参数：{}", paramsMap);
                long time = System.currentTimeMillis();
                HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                        .header("Content-Version", "1.0")
                        .header("Content-Type", "text/json;charset=utf-8")
                        .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
                long useTime = System.currentTimeMillis() - time;
                log.info("慧享佳--鉴权接口响应参数：{}；useTime：{}", response.body(), useTime);
                if (HttpStatus.HTTP_OK == response.getStatus()) {
                    JSONObject jsonObject = JSONObject.parseObject(response.body());
                    String resultCode = jsonObject.getString("resultCode");
                    if ("0".equals(resultCode)) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        token = data.getString("tokenId");
                        Integer expireTime = data.getInteger("expireTime");
                        redisTemplate.opsForValue().set("sys_huiXiangJiaToken", token, expireTime / 10, TimeUnit.MILLISECONDS);
                    } else {
                        log.error("慧享佳--鉴权请求响应数据异常：{}", jsonObject);
                    }
                } else {
                    log.error("慧享佳--鉴权请求失败，code：{}；body:{}", response.getStatus(), response.body());
                }
            } catch (Exception e) {
                log.error("慧享佳--鉴权请求异常：{}", e.getMessage(), e);
            }
        }
        token = token.replace("\"", "");
        return token;
    }


    /**
     * 授权密码和授权临时密码
     *
     * @param vo
     * @param smartLockPwd
     * @return
     */
    @Override
    public ResultBean<String> authorizationPwd(SmartLockVO vo, SmartLockPwd smartLockPwd) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--授权智能锁用户密码接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", vo.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "密码授权");
            dataMap.put("beginTime", smartLockPwd.getStartTime().getTime() / 1000);
            dataMap.put("endTime", smartLockPwd.getEndTime().getTime() / 1000);
            dataMap.put("password", AESUtil.encryptKey(token, smartLockPwd.getPassword()));
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddPasswordKey");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--添加用户接口密码授权请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.1")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--添加用户接口密码授权响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    DevMacStateVO devMacStateVO = new DevMacStateVO();
                    devMacStateVO.setPhoneNo(phoneNo);
                    devMacStateVO.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    objectResultBean.setResultData(JSONObject.toJSONString(devMacStateVO));
                } else {
                    log.error("慧享佳--授权门锁用户密码请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("授权门锁用户密码失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--授权门锁用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加用户密码响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加用户密码请求异常");
            log.error("慧享佳--授权门锁用户密码请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    /**
     * 删除密码授权
     *
     * @param vo
     * @param lockAuthId
     * @return
     */
    @Override
    public ResultBean<String> deletePwd(SmartLockVO vo, Long lockAuthId) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除智能锁用户密码接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("phoneNo", vo.getIdentification());
            dataMap.put("roomId", vo.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomSingleCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除用户接口密码授权请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除用户接口密码响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    return objectResultBean;
                } else {
                    log.error("慧享佳--删除门锁用户密码响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("删除失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--删除门锁用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("删除门锁用户密码信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除门锁用户密码信息请求异常");
            log.error("慧享佳--删除门锁用户密码请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }


    @Override
    public ResultBean<String> fingerprintUnlocking(SmartLockFingerprintVO vo) {
        return null;
    }

    @Override
    public ResultBean<String> deleteFingerprintUnlocking(SmartLockVO vo) {
        return null;
    }

    @Override
    public boolean doorCardUnlocking() {
        return false;
    }


    /**
     * 授权门卡
     *
     * @param vo
     * @param smartLockCard
     * @return
     */
    @Override
    public ResultBean<String> identityCardUnlocking(SmartLockVO vo, SmartLockCard smartLockCard) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--授权智能锁用户门卡接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            String cardNumber = smartLockCard.getCardNumber();
            // 是传16进制过来，需要转成10进制
            BigInteger bigInteger = new BigInteger(cardNumber, 16);
            cardNumber = String.valueOf(bigInteger);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", vo.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "卡片授权");
            dataMap.put("beginTime", smartLockCard.getStartTime().getTime() / 1000);
            dataMap.put("endTime", smartLockCard.getEndTime().getTime() / 1000);
            dataMap.put("cardNum", AESUtil.encryptKey(token, cardNumber));
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddCardKey");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--添加用户门卡请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.1")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--添加用户门卡响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    DevMacStateVO devMacStateVO = new DevMacStateVO();
                    devMacStateVO.setPhoneNo(phoneNo);
                    devMacStateVO.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    objectResultBean.setResultData(JSONObject.toJSONString(devMacStateVO));
                } else {
                    log.error("慧享佳--授权用户门卡请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("授权用户门卡失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--授权用户门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加用户门卡响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加用户门卡请求异常");
            log.error("慧享佳--授权用户门卡请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }


    /**
     * 删除门卡授权
     *
     * @param vo
     * @return
     */
    @Override
    public ResultBean<String> deleteIdentityCardUnlocking(SmartLockVO vo) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除智能锁门卡接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("phoneNo", vo.getIdentification());
            dataMap.put("roomId", vo.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomSingleCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除用户门卡请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除用户门卡响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    return objectResultBean;
                } else {
                    log.error("慧享佳--删除用户门卡请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("删除用户门卡失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--删除用户门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("删除用户门卡信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除用户门卡信息请求异常");
            log.error("慧享佳--删除用户门卡请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> bluetoothUnlocking(SmartLockVO vo, SmartLockBle smartLockBle) {
        return null;
    }

    @Override
    public ResultBean<String> getBluetoothUnlocking(Long lockAuthId) {
        return null;
    }


    /**
     * 获取蓝牙密钥
     *
     * @return
     */
    public ResultBean<String> getBluetoothUnlocking(String sn) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--查询设备详细信息接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", sn);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomDetail");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--查询设备详细信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--查询设备详细信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    if (jsonObject.getJSONObject("data").getString("lockMac").isEmpty()) {
                        objectResultBean.setMsg("智能锁MAC号错误");
                        return objectResultBean;
                    }
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(jsonObject.getString("data"));
                    return objectResultBean;
                } else {
                    log.error("慧享佳--查询设备详细信息请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("查询设备详细信息失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--查询设备详细信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("查询设备详细信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("查询设备详细信息请求异常");
            log.error("慧享佳--查询设备详细信息请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> deleteBluetoothUnlocking(SmartLockVO vo) {
        return null;
    }

    @Override
    public ResultBean<String> deleteAll(String mac, Long lockId) {
        return null;
    }


    /**
     * 新增授权人脸信息
     *
     * @param smartLockFace 人脸信息
     * @return
     */
    public ResultBean<String> addFaceImage(SmartLockFace smartLockFace) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--授权人脸信息接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        ResultBean<String> stringResultBean = this.uploadFile(token, smartLockFace.getFaceImage());
        if (StatusCode.ERROR_CODE_10001.getErrorCode().equals(stringResultBean.getCode())) {
            return stringResultBean;
        }
        try {
            Long startTime = smartLockFace.getStartTime() == null ? new Date().getTime() : smartLockFace.getStartTime().getTime();
            Long endTime = smartLockFace.getEndTime() == null ? this.addTime(new Date()).getTime() : smartLockFace.getEndTime().getTime();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLockFace.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "人脸授权");
            dataMap.put("beginTime", startTime / 1000);
            dataMap.put("endTime", endTime / 1000);
            dataMap.put("password", stringResultBean.getResultData());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddFace");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--授权人脸信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.3")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--授权人脸信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    DevMacStateVO devMacStateVO = new DevMacStateVO();
                    devMacStateVO.setPhoneNo(phoneNo);
                    devMacStateVO.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    objectResultBean.setResultData(JSONObject.toJSONString(devMacStateVO));
                } else {
                    log.error("慧享佳--授权人脸信息请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("授权用户门卡失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--授权人脸信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("授权人脸信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("授权人脸信息请求异常");
            log.error("慧享佳--授权人脸信息请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }


    /**
     * 修改授权人脸信息
     *
     * @param smartLockFace 人脸信息
     * @return
     */
    public ResultBean<String> updateFaceImage(SmartLockFace smartLockFace) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--修改授权人脸信息信息接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }

        ResultBean<String> resultBean = this.deleteFaceImage(smartLockFace);
        if (StatusCode.ERROR_CODE_10001.getErrorCode().equals(resultBean.getCode())) {
            return resultBean;
        }
        ResultBean<String> stringResultBean = this.uploadFile(token, smartLockFace.getFaceImage());
        if (StatusCode.ERROR_CODE_10001.getErrorCode().equals(stringResultBean.getCode())) {
            return stringResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLockFace.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "人脸授权");
            dataMap.put("beginTime", smartLockFace.getStartTime().getTime() / 1000);
            dataMap.put("endTime", smartLockFace.getEndTime().getTime() / 1000);
            dataMap.put("password", stringResultBean.getResultData());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddFace");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--授权人脸信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.1")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--授权人脸信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    DevMacStateVO devMacStateVO = new DevMacStateVO();
                    devMacStateVO.setPhoneNo(phoneNo);
                    devMacStateVO.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    objectResultBean.setResultData(JSONObject.toJSONString(devMacStateVO));
                } else {
                    log.error("慧享佳--授权人脸信息请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("授权用户门卡失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--授权人脸信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("授权人脸信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("授权人脸信息请求异常");
            log.error("慧享佳--授权人脸信息请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    /**
     * 删除授权人脸信息
     *
     * @param smartLockFace 授权人脸信息
     * @return
     */
    public ResultBean<String> deleteFaceImage(SmartLockFace smartLockFace) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除授权人脸信息接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("phoneNo", smartLockFace.getIdentification());
            dataMap.put("roomId", smartLockFace.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomSingleCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除授权人脸信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除授权人脸信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    return objectResultBean;
                } else {
                    log.error("慧享佳--删除授权人脸信息请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("删除授权人脸信息失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--删除授权人脸信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("删除授权人脸信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除授权人脸信息请求异常");
            log.error("慧享佳--删除授权人脸信息请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }


    /**
     * 根据设备id查询设备详细信息
     *
     * @param deviceId 设备id
     */
    public ResultBean<String> getLockDetail(String deviceId) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--查询设备详细信息接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", deviceId);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomDetail");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--查询设备详细信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--查询设备详细信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    if (jsonObject.getJSONObject("data").getString("lockMac").isEmpty()) {
                        objectResultBean.setMsg("智能锁MAC号错误");
                        return objectResultBean;
                    }
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(deviceId);
                    return objectResultBean;
                } else {
                    log.error("慧享佳--查询设备详细信息请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("查询设备详细信息失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--查询设备详细信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("查询设备详细信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("查询设备详细信息请求异常");
            log.error("慧享佳--查询设备详细信息请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }


    /**
     * 根据设备id查询设备详细信息,返回智能锁信息
     *
     * @param deviceId 设备id
     */
    public ResultBean<DevMacStateVO> getLockDetailInfo(String deviceId) {
        String token = this.getToken();
        ResultBean<DevMacStateVO> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--查询设备详细信息接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", deviceId);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomDetail");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--查询设备详细信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--查询设备详细信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    if (jsonObject.getJSONObject("data").getString("lockMac").isEmpty()) {
                        objectResultBean.setMsg("智能锁MAC号错误");
                        return objectResultBean;
                    }
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    DevMacStateVO devMacStateVO = new DevMacStateVO();
                    devMacStateVO.setState(1);
                    devMacStateVO.setBattery(Integer.valueOf(jsonObject.getJSONObject("data").getString("electricNum")));
                    devMacStateVO.setLockSn(jsonObject.getJSONObject("data").getString("lockMac"));
                    objectResultBean.setResultData(devMacStateVO);
                    return objectResultBean;
                } else {
                    log.error("慧享佳--查询设备详细信息请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("查询设备详细信息失败：" + jsonObject.getString("reason"));
                }
            } else {
                log.error("慧享佳--查询设备详细信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("查询设备详细信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("查询设备详细信息请求异常");
            log.error("慧享佳--查询设备详细信息请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }


    /**
     * 人脸上传接口
     *
     * @param token    token
     * @param imageUrl 人脸路径
     * @return
     */
    public ResultBean<String> uploadFile(String token, String imageUrl) {
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        try {

            // 获取图片二进制
            imageUrl = imageUrl.split("https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/")[1];
            OSSObject object = ossClient.getObject("xj-saas-images", imageUrl);
            File file = File.createTempFile("stream2file", ".jpg");
            try (FileOutputStream out = new FileOutputStream(file)) {
                IOUtils.copy(object.getObjectContent(), out);
            }
            byte[] imageBytes = FileUtils.readFileToByteArray(file);
            String face = Base64.encodeBase64String(imageBytes);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("password", face);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentFaceImageUpload");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--人脸图片处理请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.3")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--人脸图片处理响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(jsonObject.getJSONObject("data").getString("password"));
                    return objectResultBean;
                } else {
                    log.error("慧享佳--人脸图片处理请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("人脸图片处理失败：" + jsonObject.getString("message"));
                }
            } else {
                log.error("慧享佳--人脸图片处理请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("人脸图片处理响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("人脸图片处理请求异常");
            log.error("慧享佳--人脸图片处理请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    public Date addTime(Date nowTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowTime);
        calendar.add(Calendar.YEAR, 10);
        return calendar.getTime();
    }
}
